import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {getParams} from './params'
import {getROSClient, Ros} from './ros'
import {checkStackExist} from './checkStackExist'
import {createStack} from './createStack'
import {updateStack} from './updateStack'
import {validateTemplate} from './validateTemplate'

async function runStep(): Promise<void> {
    const params = getParams()
    step.info(`PIPELINE_ID=${params.pipelineID}`)
    step.info(`PIPELINE_NAME=${params.pipelineName}`)
    step.info(`BUILD_NUMBER=${params.buildNumber}`)
    step.info(`WORK_SPACE=${params.workSpace}`)
    step.info(`PROJECT_DIR=${params.projectDir}`)
    step.info(`BUILD_JOB_ID=${params.buildJobID}`)
    step.info(`REGION_ID=${params.REGION_ID}`)


    step.info(`ROS_DEPLOYMENT_LOCATION=${params.ROS_DEPLOYMENT_LOCATION}`)
    step.info(`RAM_ROLE_NAME=${params.RAM_ROLE_NAME}`)
    step.info(`STACK_NAME=${params.STACK_NAME}`)
    step.info(`ROS_STACK_FILE_PATH=${params.ROS_STACK_FILE_PATH}`)
    step.info(`TIMEOUT_MINUTES=${params.TIMEOUT_MINUTES}`)

    const rosClient = await getROSClient()
    const ros = new Ros(rosClient)

    const stackId = await checkStackExist(params, ros)
    if (stackId) {
        const updateStackId = await updateStack(params, ros, stackId);
        if (updateStackId) {
            step.info(`STACK_NAME=${params.STACK_NAME}, STACK_ID=${updateStackId} is updating.`);
        } else {
            process.exit(-1);
        }
    } else {
        const validateRes = await validateTemplate(params, ros);
        if (validateRes) {
            step.info(`ValidateTemplate succeeded. About to create stack: ${params.STACK_NAME}`);
            const createStackId = await createStack(params, ros);
            if (createStackId) {
                step.info(`STACK_NAME=${params.STACK_NAME}, STACK_ID=${createStackId} is creating.`);
            } else {
                process.exit(-1);
            }
        } else {
            process.exit(-1);
        }
    }


}

runStep()
    .then(function() {
        step.success('run step successfully!')
    })
    .catch(function(err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
